package com.syq.controller;

import com.syq.captcha.CaptchaCodeManager;
import com.syq.pojo.DtsAdmin;
import com.syq.service.DtsRoleService;
import com.syq.util.*;
import com.syq.util.Base64;
import com.syq.util.UUID;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * @ClassName: AdminAuthController
 * @Description: TODO
 * @Create by: syq
 * @Date: 2022/7/21 15:21
 */

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminAuthController {

    @Autowired
    private DtsRoleService dtsRoleService;

    //获取验证码
    @GetMapping("/auth/captchaImage")
    public Object getCode() throws IOException {
        Map<String,Object> map=new HashMap<>();

        //获取验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //2:将code保存在map中
        String uuid = UUID.randomUUID(true).toString();
        boolean flag = CaptchaCodeManager.addToCache(uuid, code, 1);
        if (flag){
            //将code生成图片
            int w=111;
            int h=36;
            //图片存放在os中
            ByteArrayOutputStream os=new ByteArrayOutputStream();
            //将图片写在os中
            VerifyCodeUtils.outputImage(w,h,os,code);
            map.put("img",Base64.encode(os.toByteArray()));
            map.put("uuid",uuid);
        }

        return ResponseUtil.ok(map);
    }

    //登录
    @PostMapping("/auth/login")
    public Object login(@RequestBody String json){
        String username = JacksonUtil.parseString(json, "username");
        String password = JacksonUtil.parseString(json, "password");
        String code = JacksonUtil.parseString(json, "code");
        String uuid = JacksonUtil.parseString(json, "uuid");

        //1.判断code 验证码是否正确
        String codeCache = CaptchaCodeManager.getCachedCaptcha(uuid);
        //判断验证码是否为空
        if (StringUtils.isEmpty(codeCache)){
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_EXPIRED);
        }
        //判断验证码是否正确
        if (!codeCache.equalsIgnoreCase(code)){
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_ERROR);
        }
        //校验
        Subject subject = SecurityUtils.getSubject();

        //加密

        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);

        try {
            subject.login(usernamePasswordToken);
        } catch (LockedAccountException e) {
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_LOCK_ACCOUNT);
        }
//        }catch (AuthenticationException e) {
//            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
//        }

        DtsAdmin dtsAdmin = (DtsAdmin) subject.getPrincipal();

        //ResponseUtil 统一返回值对象


        return ResponseUtil.ok(subject.getSession().getId());//统一返回值对象
    }

    @PostMapping("/auth/logout")
    public Object logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResponseUtil.ok();
    }
    //权限信息
    @GetMapping("auth/info")
    public Object info(){
        Map<String,Object> map=new HashMap<>();
        Subject subject = SecurityUtils.getSubject();
        DtsAdmin admin = (DtsAdmin) subject.getPrincipal();

        Set<String> roles=dtsRoleService.findRolesByUid(admin.getId());

        map.put("roles",roles);
        map.put("name", admin.getUsername());
        map.put("perms", Arrays.asList("*"));
        map.put("avatar", admin.getAvatar());
        return ResponseUtil.ok(map);
    }

    //返回权限不足
    @GetMapping("auth/403")
    public Object auth403(){
        return ResponseUtil.unauthz();
   }
}
